import {getRequest} from './http';
import md5 from 'js-md5';
import {translate, BAIDU} from './api';
//日期时间格式化 传入new Date() 则是当前时间
export const FormatDate = (value, type) => {
  window.Date.prototype.Format = function (fmt) {
    let o = {
      "M+": this.getMonth() + 1, // 月份
      "d+": this.getDate(), // 日
      "H+": this.getHours(), // 小时
      "m+": this.getMinutes(), // 分
      "s+": this.getSeconds(), // 秒
      "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
      "S": this.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
      if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  };
  if (type === 'date') {//返回日期
    return value.Format("yyyy-MM-dd");
  }
  else if (type === 'time') {//返回时间
    return value.Format("HH:mm:ss");
  }
  else {//返回日期时间
    return value.Format("yyyy-MM-dd HH:mm:ss");
  }
};
//获取两个日期之间所有的日期
export const GetAllDate = (begin, end, type) => {
  let arr = [];
  let ab = begin.split("-");
  let ae = end.split("-");
  let db = new Date();
  db.setUTCFullYear(ab[0], ab[1] - 1, ab[2]);
  let de = new Date();
  de.setUTCFullYear(ae[0], ae[1] - 1, ae[2]);
  let unixDb = db.getTime() - 24 * 60 * 60 * 1000;
  let unixDe = de.getTime() - 24 * 60 * 60 * 1000;
  for (let k = unixDb; k <= unixDe;) {
    k = k + 24 * 60 * 60 * 1000;
    if (type === 'date') {
      arr.push(FormatDate(new Date(parseInt(k)), type));
    }
    else {
      arr.push(FormatDate(new Date(parseInt(k))));
    }
  }
  return arr;
};
//多维数组转化为一维数组,arr数组,key子级数组属性名,type是否包含父级
export const Flatten = (arr, key, type) => {
  let res = [];
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i][key])) {
      if (type) res.push(arr[i]);
      res = res.concat(Flatten(arr[i][key], key, type));
      if (type) delete arr[i][key];
    }
    else {
      res.push(arr[i]);
    }
  }
  return res;
};
//遍历循环数组,判断权限中有多少为true,动态改变width;
export const ObjectTrue = (obj) => {
  const arr = [];
  for (let key in obj) {
    if (obj[key]) {
      arr.push(obj[key]);
    }
  }
  return arr.length;
};
//调用百度翻译接口
export const Translate = async (query, from, to) => {
  /*
  query  需要翻译的文本
  from  需要翻译的文本语言类型,默认 中文(zh)
  to  需要翻译成什么语言类型,默认 英语(en)
  */
  const appid = '20200420000424953';
  const key = 'P4MBWPDj1sYZ_JHQThx6';
  const salt = (new Date).getTime();
  const sign = md5(appid + query + salt + key);
  const data = {
    q: query,
    appid: appid,
    salt: salt,
    from: from ? from : "zh",
    to: to ? to : "en",
    sign: sign
  };
  return await getRequest(translate, data, BAIDU).then(res => res.trans_result);
};
/*
  导出excel表格 安装
  npm install -S file-saver
  npm install -S xlsx
  npm install -D script-loader
*/
export const ImportExcel = (tHeader, filterVal, data, name) => {
  /* tHeader 导出的表头名
   filterVal 导出的表头对应的字段名
   data 导出的数据
   name 导出的表格名称，根据需要自己命名*/
  require.ensure([], () => {
    const {export_json_to_excel} = require('../plugIn/excel/Export2Excel.js');
    const list = data.map(v => filterVal.map(j => v[j]));
    const title = `${name}(${FormatDate(new Date(), "date")})`;
    export_json_to_excel(tHeader, list, title);
  })
};
//数字格式化,超过万显示万,超过亿显示亿,超过万亿显示万亿
export const NumberFormat = (value) => {
  let param = {};
  let k = 10000,
    sizes = ['', '万', '亿', '万亿', '兆', '十兆', '百兆', '千兆', '京', '十京', '百京', '千京', '垓', '十垓', '百垓', '千垓'],
    i;
  if (value > 0) {
    if (value < k) {
      param.value = value;
      param.unit = ''
    }
    else {
      i = Math.floor(Math.log(value) / Math.log(k));
      param.value = ((value / Math.pow(k, i))).toFixed(2);
      param.unit = sizes[i];
    }
  }
  else {
    if (-value < k) {
      param.value = value;
      param.unit = ''
    }
    else {
      i = Math.floor(Math.log(-value) / Math.log(k));
      param.value = ((value / Math.pow(k, i))).toFixed(2);
      param.unit = sizes[i];
    }
  }
  return param;
};
export const EqualFormat = (max, min) => {
  let param = {};
  let k = 10000,
    sizes = ['', '万', '亿', '万亿', '兆', '十兆', '百兆', '千兆', '京', '十京', '百京', '千京', '垓', '十垓', '百垓', '千垓'],
    i;
  if (min > 0) {
    if (min < k) {
      param.value = max;
      param.unit = ''
    }
    else {
      i = Math.floor(Math.log(min) / Math.log(k));
      param.value = ((max / Math.pow(k, i))).toFixed(2);
      param.unit = sizes[i];
    }
  }
  else {
    if (-min < k) {
      param.value = max;
      param.unit = ''
    }
    else {
      i = Math.floor(Math.log(-min) / Math.log(k));
      param.value = ((max / Math.pow(k, i))).toFixed(2);
      param.unit = sizes[i];
    }
  }
  return param;
};

// 价格校验
export const validatPrices = (rule, value, callback) => {
  if (rule.required === false && (value === '' || value === null || value === undefined)) {
    callback()
  }
  const isPrice = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/
  if (isPrice.test(value)) {
    callback()
  } else {
    callback(new Error(rule.message || '请输入正确的价格，例：10, 10.00'))
  }
}